package com.yt.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.ZonedDateTime;

/**
 * @Classname MyFilter
 * @Description
 * @Date 2021/10/22 19:24
 * @Create by 杨涛
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    /**
     * ServerWebExchange 对象，相当于requests和response的合体
     * GatewayFilterChain 对象，是过滤器链
     * Order 编号 是执行顺序。
     */
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始过滤 。。。 "+ ZonedDateTime.now());
        String name=exchange.getRequest().getQueryParams().getFirst("uname");
        if(name==null){
            log.info("没有用户，不准通过。");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            exchange.getResponse().setComplete();
        }
        //通过，交给下一个环节
        return chain.filter(exchange);
    }

    //过滤链的第几环，越小越先
    @Override
    public int getOrder() {
        return 0;
    }
}
